<template>
  <div class="dcy-content">
    <!-- 查询条件 -->
    <Form ref="queryParams" :model="queryParams" inline :label-width="60" label-position="left">
      <FormItem label="名称">
        <Input v-model="queryParams.powName" clearable placeholder="请输入权限名称"/>
      </FormItem>
      <FormItem :label-width="0" class="search-btn-mar">
        <Button icon="md-search"  type="primary" @click="refresh()">查询</Button>
        <Button icon="md-refresh"  type="primary" @click="reset()">重置</Button>
        <Button icon="md-add" type="primary"  @click="addUser()">添加</Button>
        <Button icon="md-add" type="primary"  @click="removeBatch()" :disabled="delBtnDisabled">删除</Button>
      </FormItem>
    </Form>

    <!-- 表格 -->
    <dcy-table
      ref="dcyTable"
      unique-id="powId"
      :query-params="queryParams"
      :url="url"
      @table-select-val="selectVal"
      :columns="columns">
      <template slot-scope="{ row, index }" slot="powType">
        <Tag color="blue" v-if="row.powType === '0'">模块权限</Tag>
        <Tag color="green" v-if="row.powType === '1'">菜单权限</Tag>
      </template>
      <template slot-scope="{ row, index }" slot="powStatus">
        <Tag color="success" v-if="row.powStatus === '0'">正常</Tag>
        <Tag color="error" v-if="row.powStatus === '1'">禁用</Tag>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <a @click="update(row)">修改</a>
        <Divider type="vertical"/>
        <a @click="remove(row)">删除</a>
        <Divider type="vertical" v-if="row.powType === '0'"/>
        <a @click="authModule(row)" v-if="row.powType === '0'">授权模块</a>
        <Divider type="vertical" v-if="row.powType === '1'"/>
        <a @click="authMenu(row)" v-if="row.powType === '1'">授权菜单</a>
      </template>
    </dcy-table>

    <!-- 添加表单 -->
    <Modal
      v-model="dialogShow"
      :title="dialogTitle"
      :mask-closable="false"
      @on-cancel="handleReset('form')">
      <Form ref="form" :model="form" :rules="rules" :label-width="80">
        <FormItem label="权限名称" prop="powName">
          <Input v-model="form.powName" placeholder="请输入权限类型"/>
        </FormItem>
        <FormItem label="权限类型" prop="powType">
          <Select v-model="form.powType" placeholder="请选择权限类型">
            <template v-for="item in powerTypeOptionList">
              <Option :value="item.dictValue">{{item.dictLable}}</Option>
            </template>
          </Select>
        </FormItem>
        <FormItem label="状态" prop="powStatus">
          <Select v-model="form.powStatus" placeholder="请选择状态">
            <template v-for="item in statusOptionList">
              <Option :value="item.dictValue">{{item.dictLable}}</Option>
            </template>
          </Select>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input v-model="form.remark" placeholder="请输入备注"/>
        </FormItem>
      </Form>
      <!-- 自定义按钮组 -->
      <div slot="footer">
        <Button type="text"  @click="handleReset('form')">取消</Button>
        <Button type="primary"  @click="handleSubmit('form')">确认</Button>
      </div>
    </Modal>


    <!-- 授权模块 -->
    <Modal
      v-model="dialogModuleShow"
      title="授权模块"
      :scrollable="true"
      :mask-closable="false"
      @on-ok="saveAuthModule"
      @on-cancel="dialogModuleShow = false">
      <Tree ref="dcyModuleTree" :data="moduleData" show-checkbox></Tree>
    </Modal>

    <!-- 授权菜单 -->
    <Modal
      v-model="dialogMenuShow"
      title="授权模块"
      :scrollable="true"
      :mask-closable="false"
      @on-ok="saveMenuModule"
      @on-cancel="dialogMenuShow = false">
      <Tree ref="dcyMenuTree" :data="menuData" show-checkbox></Tree>
    </Modal>
  </div>
</template>

<script>
    import DcyTable from '@/components/dcy/dcy-table'
    import {addPower, deleteBatchPowerById, deletePowerById, updatePower} from '@/api/admin/power'
    import {noticeError, noticeSuccess} from '@/libs/notice'
    import {getModuleTreeList} from "../../api/admin/module";
    import {saveAuthMenu, saveAuthModule} from "../../api/admin/power";
    import {getMenuTreeList} from "../../api/admin/menu";
    import {getDictByType} from "../../api/common";

    export default {
        name: 'power-manage',
        components: {DcyTable},
        data() {
            return {
                url: '/admin-service/power/page',
                columns: [
                    {title: '权限名称', key: 'powName', align: 'center'},
                    {title: '权限类型', slot: 'powType', align: 'center'},
                    {title: '状态', slot: 'powStatus', align: 'center'},
                    {title: '操作', slot: 'action', align: 'center'}
                ],
                queryParams: {},
                dialogShow: false,
                dialogModuleShow: false,
                dialogMenuShow: false,
                delBtnDisabled: true,
                ids: [],
                dialogTitle: '添加用户',
                form: {},
                rules: {
                    powName: [this.$ruler('权限名称')],
                    powType: [this.$ruler('权限类型')],
                    powStatus: [this.$ruler('状态', 'change')],
                },
                moduleData: [],
                menuData: [],
                powerId: null,
                statusOptionList:[],
                powerTypeOptionList:[]
            }
        },
        methods: {
            /**
             * 刷新
             */
            refresh() {
                // 清空选中状态
                this.$refs.dcyTable.selectAll(false);
                this.$refs.dcyTable.refresh()
            },
            /**
             * 重置搜索条件
             */
            reset() {
                this.queryParams = {}
            },
            /**
             * 修改弹出框
             * @param row
             */
            update(row) {
                this.form = {...row};
                this.dialogTitle = '修改权限';
                this.dialogShow = true
            },
            /**
             * 添加弹出框
             */
            addUser() {
                this.dialogTitle = '添加权限';
                this.dialogShow = true
            },
            /**
             * 批量删除
             */
            removeBatch() {
                this.$Modal.confirm({
                    title: '您确认删除所选内容吗？',
                    onOk: () => {
                        deleteBatchPowerById(this.ids).then(res => {
                            if (res.data) {
                                noticeSuccess('del')
                            } else {
                                noticeError('del')
                            }
                            this.refresh()
                        })
                    }
                })
            },
            /**
             * 提交表单
             * @param name
             */
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        if (this.dialogTitle === '添加权限') {
                            addPower(this.form).then(res => {
                                if (res.data) {
                                    noticeSuccess('add')
                                } else {
                                    noticeError('add')
                                }
                                this.cancelDialogAndRefresh()
                            })
                        } else {
                            updatePower(this.form).then(res => {
                                if (res.data) {
                                    noticeSuccess('upd')
                                } else {
                                    noticeError('upd')
                                }
                                this.cancelDialogAndRefresh()
                            })
                        }
                    }
                })
            },
            /**
             * 行内删除
             * @param row
             */
            remove(row) {
                this.$Modal.confirm({
                    title: '您确认删除这条内容吗？',
                    onOk: () => {
                        deletePowerById(row.powId).then(res => {
                            if (res.data) {
                                noticeSuccess('del')
                            } else {
                                noticeError('del')
                            }
                            this.refresh()
                        })
                    }
                })
            },
            /**
             * 重置表单
             * @param name
             */
            handleReset(name) {
                this.form = {};
                this.dialogShow = false;
                this.$refs[name].resetFields()
            },
            /**
             * 关闭弹出框 和 刷新表格
             */
            cancelDialogAndRefresh() {
                // 关闭弹出框 和 清空表单
                this.handleReset('form');
                // 刷新表格
                this.refresh()
            },
            /**
             * 点击每一行的checkbox
             */
            selectVal(ids) {
                this.ids = ids
                this.delBtnDisabled = !this.ids.length
            },
            /**
             * 授权模块
             * @param row
             */
            authModule(row) {
                this.powerId = row.powId;
                this.dialogModuleShow = true;
                getModuleTreeList(this.powerId).then(res => {
                    this.moduleData = res.data;
                })
            },
            saveAuthModule() {
                // 获取选中及半选节点
                let moduleIds = [];
                this.$refs.dcyModuleTree.getCheckedAndIndeterminateNodes().forEach(e => {
                    // 只取菜单类型得
                    if (e.type === '1') {
                        moduleIds.push(e.id);
                    }
                });
                let powerModuleDTO = {
                    powerId: this.powerId,
                    moduleIds: moduleIds
                };
                saveAuthModule(powerModuleDTO).then(res => {
                    if (res.data) {
                        noticeSuccess('d')
                    } else {
                        noticeError('d')
                    }
                    // 刷新表格
                    this.refresh()
                })
            },
            /**
             * 授权菜单
             * @param row
             */
            authMenu(row){
                this.powerId = row.powId;
                this.dialogMenuShow = true;
                getMenuTreeList(this.powerId).then(res => {
                    this.menuData = res.data;
                })
            },
            saveMenuModule(){
                // 获取选中及半选节点
                let menuIds = [];
                this.$refs.dcyMenuTree.getCheckedAndIndeterminateNodes().forEach(e => {
                    // 只取菜单类型得
                    if (e.type === '1') {
                        menuIds.push(e.id);
                    }
                });
                let powerMenuDTO = {
                    powerId: this.powerId,
                    menuIds: menuIds
                };
                saveAuthMenu(powerMenuDTO).then(res => {
                    if (res.data) {
                        noticeSuccess('d')
                    } else {
                        noticeError('d')
                    }
                    // 刷新表格
                    this.refresh()
                })
            }
        },
        mounted() {
            getDictByType('status').then(res=>{
                this.statusOptionList = res.data;
            });
            getDictByType('power_type').then(res=>{
                this.powerTypeOptionList = res.data;
            })
        }
    }
</script>

<style scoped>

</style>
